package com.zcc.makingfriend.service.impl;

import com.zcc.makingfriend.service.AttachmentService;
import com.zcc.makingfriend.untils.MinioProperties;
import io.minio.*;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zcc
 */
@Service
public class AttachmentServiceImpl implements AttachmentService {
    private MinioProperties minioProperties;
    private MinioClient minioClient;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    @Autowired
    public AttachmentServiceImpl(MinioProperties minioProperties) {
        this.minioProperties = minioProperties;
        // 创建minio客户端
        minioClient = MinioClient
                .builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(
                        minioProperties.getAccessKey(),
                        minioProperties.getSecretKey()
                ).build();

        // 创建bucket
        try {
            BucketExistsArgs beArgs = BucketExistsArgs
                    .builder()
                    .bucket(minioProperties.getBucketName())
                    .build();
            if (!minioClient.bucketExists(beArgs)) {
                minioClient.makeBucket(
                        MakeBucketArgs
                                .builder()
                                .bucket(minioProperties.getBucketName())
                                .build()
                );
            }
        } catch (MinioException | NoSuchAlgorithmException | InvalidKeyException | IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    @Override
    public List<String> upload(MultipartFile[] files) {
        System.out.println(minioProperties.getBucketName() + "cc111");
        List<String> fileUrlList = new ArrayList<>();
        for (MultipartFile file : files) {
            try (InputStream fileStream = file.getInputStream()) {
                // 保存文件最终的url
                String filename = file.getOriginalFilename();
                String objectName = sdf.format(new Date()) + "/" + filename;
                String fileUrl = "http://8.130.123.79:8090/attachment/download?objectName=" + objectName;
                fileUrlList.add(fileUrl);

                // 保存文件
                long size = Integer.toUnsignedLong(fileStream.available());
                minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(minioProperties.getBucketName())
                                .object(objectName)
                                .stream(fileStream, size, -1)
                                .contentType(file.getContentType())
                                .build()
                );
            } catch (Exception e) {
                System.out.println("Attachment upload error: " + e.getMessage());
            }
        }
        return fileUrlList;
    }

    @Override
    public int download(HttpServletResponse resp, String objectName) {
        try (
                InputStream input = minioClient.getObject(
                        GetObjectArgs.builder()
                                .bucket(minioProperties.getBucketName())
                                .object(objectName)
                                .build()
                );
                OutputStream output = resp.getOutputStream()
        ) {
            // 设置响应头
            resp.reset();
            resp.setHeader(
                    "Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(objectName, "UTF-8")
            );
            resp.setCharacterEncoding("utf-8");

            // 读取数据
            int length = 0;
            byte[] buffer = new byte[1024];
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
        } catch (Exception e) {
            System.out.println("Attachment download error: " + e.getMessage());
            return 500;
        }
        return 200;
    }
}
